import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { getPermissionList } from '@/api/permissions'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, payload) {
      // try {
      //   const token = await login(payload)
      //   // console.log(token)
      //   context.commit('setToken', token)
      // } catch (error) {
      //   console.log('~~~~~~~~~~~~~~')
      // // 密码输错也能跳转解决办法
      //   return Promise.reject(error)
      // }

      // 上面和下面完全等价
      const token = await login(payload)
      context.commit('setToken', token)
      setTimeStamp()
    },
    async getUserInfo({ commit }) {
      const userInfo = await getUserInfo()

      const userDetailInfo = await getUserDetailById(userInfo.userId)
      const baseInfo = {
        ...userInfo,
        ...userDetailInfo
      }

      const r = (await getPermissionList()).filter(item => item.enVisible === '1')
      const arr = []
      r.forEach(({ code }) => arr.push(code))
      baseInfo.roles.menus = (baseInfo.roles.menus).filter(item => arr.includes(item))

      commit('setUserInfo', baseInfo)

      return baseInfo
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      resetRouter()
      commit('permissions/setRoutes', [], {
        root: true
      })
    }
  }
}

